package com.jdd.modules.parking.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.entity.params.ImportParams;
import com.jdd.common.util.excel.util.ExcelImportUtil;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.parking.entity.ParkArmInfo;
import com.jdd.modules.parking.entity.ParkWorkStation;
import com.jdd.modules.parking.service.IParkWorkStationService;
import com.jdd.modules.parking.vo.ParkWorkStationVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 工作站
 * @Author: jdd
 * @Date:   2021-11-05
 * @Version: V1.0
 */
@Slf4j
@Api(tags="工作站")
@RestController
@RequestMapping("/parking/parkWorkStation")
public class ParkWorkStationController {
	 @Resource
	private IParkWorkStationService parkWorkStationService;

	 /** 功能描述: 判断当前用户是否已经选过工作站
	  * @Author: lcy
	  * @Date: 2021/11/5
	  */
	 @GetMapping("/checkStationAuth")
	 public Result<Object> checkStationAuth(){
		 try {
		 	 return Result.ok().setResult(parkWorkStationService.checkStationAuth());
		 }catch (Exception e){
			 return Result.error("请检查网络");
		 }
	 }

	/** 功能描述: 得到未使用得工作站信息
	 * @Author: lcy
	 * @Date: 2021/11/5
	 */
	@GetMapping("/noUseWorkStation")
	public Result<List<ParkWorkStation>> noUseWorkStation(){
		Result<List<ParkWorkStation>> result = new Result<>();
		try {
			List<ParkWorkStation> parkWorkStations = parkWorkStationService.noUseWorkStation();
			if(ObjectUtil.isEmpty(parkWorkStations)){
				result.error500("当前工作站数据为空或者都在线");
			}else{
				result.setResult(parkWorkStations);
				result.setSuccess(true);
			}
		}catch (Exception e){
			result.error500("当前工作站数据为空或者都在线");
		}
		return result;
	}
	 /** 功能描述: 用户绑定工作站信息，用于用户还没绑定工作站
	  * @Author: lcy
	  * @Date: 2021/11/5
	  */
	@PostMapping("/bindWorkStation")
	public Result<?> bindWorkStation(@RequestBody ParkWorkStation parkWorkStation){
		Result<?> result = new Result<>();
		try {
			return parkWorkStationService.bindWorkStation(parkWorkStation);
		}catch (Exception e){
			return result.error500("请检查网络后刷新重试");
		}
	}
	 /** 功能描述: 登录人有工作站选择自己工作站
	  * @Author: lcy
	  * @Date: 2021/12/30
	  */
	 @PostMapping("/bindWorkStationNoSelect")
	 public Result<?> bindWorkStationNoSelect(){
		 Result<?> result = new Result<>();
		 try {
			 return parkWorkStationService.bindWorkStationNoSelect();
		 }catch (Exception e){
			 return result.error500("请检查网络后刷新重试");
		 }
	 }
	/*** 功能描述: 删除前查询状态
	 * @param id 主键
	 * @Author: lcy
	 * @Date: 2021/11/8
	 */
	@GetMapping("/beforeDelete")
	public Result<?> beforeDelete(@RequestParam(name="id",required=true) String id){
		Result<?> result = new Result<>();
		boolean flag = parkWorkStationService.beforeDelete(id);
		//结果false则不可删除
		//结果true则可以删除
		if(flag){
			return result.success("当前工作站可以删除");
		}else{
			return result.error500("请取消绑定车道后再删除");
		}
	}

	 /*** 功能描述: 获取车道信息并处理名字，添加或编辑工作站显示车道用
	  * @Author: lcy
	  * @Date: 2021/11/8
	  */
	 @GetMapping("/getParkArmInfos")
	 public Result<?> getParkArmInfos(){
		 List<ParkArmInfo> parkArmInfos = parkWorkStationService.getParkArmInfos();
		 if(ObjectUtil.isEmpty(parkArmInfos)){
			 return Result.error("未查询到信息");
		 }
		 return Result.ok(parkArmInfos);
	 }
	/**
	  * 分页列表查询
	 * @param parkWorkStation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "工作站-分页列表查询")
	@ApiOperation(value="工作站-分页列表查询", notes="工作站-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ParkWorkStation>> queryPageList(ParkWorkStation parkWorkStation,
														@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
														@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
														HttpServletRequest req) {
		Result<IPage<ParkWorkStation>> result = new Result<IPage<ParkWorkStation>>();
		QueryWrapper<ParkWorkStation> queryWrapper = QueryGenerator.initQueryWrapper(parkWorkStation, req.getParameterMap());
		Page<ParkWorkStation> page = new Page<ParkWorkStation>(pageNo, pageSize);
		IPage<ParkWorkStation> pageList = parkWorkStationService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 添加
	  *
	  * @param parkWorkStationVo
	  * @return
	  */
	 @AutoLog(value = "工作站-添加")
	 @ApiOperation(value = "工作站-添加", notes = "工作站-添加")
	 @PostMapping(value = "/add")
	 @OperationLogDetail(detail = "工作站，添加", level = LogLevelType.ONE, operationType = OperationType.INSERT, operationUnit = OperationUnit.UNKNOWN)
	 public Result<ParkWorkStation> add(@RequestBody ParkWorkStationVo parkWorkStationVo) {
		 Result<ParkWorkStation> result = new Result<ParkWorkStation>();
		 try {
			 if (parkWorkStationService.saveWorkStationFrom(parkWorkStationVo)) {
				 result.success("添加成功！");
			 } else {
				 result.error500("工作站重名或没有车场配置或车道已经被别人选用，添加失败");
			 }
		 } catch (Exception e) {
			 log.error("工作站add方法报错");
			 result.error500("添加工作站失败");
		 }
		 return result;
	 }

	 /**
	  * 编辑
	  *
	  * @param parkWorkStationVo
	  * @return
	  */
	 @AutoLog(value = "工作站-编辑")
	 @ApiOperation(value = "工作站-编辑", notes = "工作站-编辑")
	 @PutMapping(value = "/edit")
	 @OperationLogDetail(detail = "工作站，编辑", level = LogLevelType.ONE, operationType = OperationType.UPDATE, operationUnit = OperationUnit.UNKNOWN)
	 public Result<ParkWorkStation> edit(@RequestBody ParkWorkStationVo parkWorkStationVo) {
		 Result<ParkWorkStation> result = new Result<ParkWorkStation>();
		 try {
			 if (parkWorkStationService.updateWorkStationFrom(parkWorkStationVo)) {
				 result.success("编辑工作站成功");
			 } else {
				 result.error500("工作站在线或选择的车道已被别人选择，无法编辑");
			 }
		 } catch (Exception e) {
			 log.error("编辑工作站报错");
			 result.error500("编辑工作站失败");
		 }
		 return result;
	 }

	 /**
	  * 通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "工作站-通过id删除")
	 @ApiOperation(value = "工作站-通过id删除", notes = "工作站-通过id删除")
	 @DeleteMapping(value = "/delete")
	 @OperationLogDetail(detail = "工作站，通过id删除", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
	 public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		 Result<ParkWorkStation> result = new Result<ParkWorkStation>();
		 try {
			 if (parkWorkStationService.removeWorkStationFrom(id)) {
				 result.success("工作站-通过id删除成功");
			 } else {
				 result.error500("工作站-通过id删除失败");
			 }
		 } catch (Exception e) {
			 log.error("工作站-通过id删除失败");
			 result.error500("工作站-通过id删除失败");
		 }
		 return result;
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "工作站-通过id查询")
	 @ApiOperation(value = "工作站-通过id查询", notes = "工作站-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<ParkWorkStationVo> queryById(@RequestParam(name = "id", required = true) String id) {
		 Result<ParkWorkStationVo> result = new Result<ParkWorkStationVo>();
		 ParkWorkStationVo parkWorkStation = parkWorkStationService.getWorkStationFrom(id);
		 if (parkWorkStation == null) {
			 result.error500("未找到对应实体");
		 } else {
			 result.setResult(parkWorkStation);
			 result.setSuccess(true);
		 }
		 return result;
	 }

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response,ParkWorkStation parkWorkStation) {
      // Step.1 组装查询条件
       QueryWrapper<ParkWorkStation> queryWrapper = QueryGenerator.initQueryWrapper(parkWorkStation, request.getParameterMap());

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
      List<ParkWorkStation> pageList = parkWorkStationService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "工作站列表");
      mv.addObject(NormalExcelConstants.CLASS, ParkWorkStation.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工作站列表数据", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
	  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	  Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	  for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		  // 获取上传文件对象
		  MultipartFile file = entity.getValue();
		  ImportParams params = ImportParams.builder().build();
		  params.setTitleRows(2);
		  params.setHeadRows(1);
		  params.setNeedSave(true);
		  try {
			  List<ParkWorkStation> listParkWorkStations = ExcelImportUtil.importExcel(file.getInputStream(), ParkWorkStation.class, params);
			  parkWorkStationService.saveBatch(listParkWorkStations);
			  return Result.ok("文件导入成功！数据行数:" + listParkWorkStations.size());
		  } catch (Exception e) {
			  log.error(e.getMessage(), e);
			  return Result.error("文件导入失败:" + e.getMessage());
		  } finally {
			  try {
				  file.getInputStream().close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
	  }
      return Result.ok("文件导入失败！");
  }

}
